<?php
	session_start();
	$message = "";
	require('config/mysql.config.inc');
	$mysqli= new mysqli($host, $username, $password, $db);
	$message= "";
	//Set up the vars for the menubar displaying page content
	$page=null;
		
	if(isset($_GET['page']) && $_GET['page']=='diningroom'){
		$page= "Dining Room";
		$welcome= "Welcome to the Dining Room Furniture page. Please feel free to browse the items below:";		
	}
	elseif(isset($_GET['page']) && $_GET['page']=='kitchen'){
		$page= "Kitchen";
		$welcome= "Welcome to the Kitchen Furniture page. Please feel free to browse the items below:";	
	}
	elseif(isset($_GET['page']) && $_GET['page']=='misc'){
		$page= "Islands and Misc.";
		$welcome="Welcome to the Miscellaneous Furniture and Islands page. Please feel free to browse the items below:";
	}
	else{
		$welcome="Please select a furniture set from the tabs above.";
	}
	$query= "SELECT categoryid FROM CategoryTypes WHERE cname= '".$page."'";
	$result= $mysqli->query($query);
	$temp= $result->fetch_assoc();
	$categoryid= $temp['categoryid'];
	include ('includes/header.php');
	include('includes/menubar.php');
	print("\n");
	
	function makeThumb($imgpath){
		$img = imagecreatefromjpeg($imgpath);
		$imgpathexplode = explode("/", $imgpath);
		$width = imagesx($img);
		$height = imagesy($img);

		$thumb_height = 200;

		$new_height = $thumb_height;
		$new_width = floor($width * ($thumb_height/$height));

		$new_img = imagecreatetruecolor($new_width, $new_height);

		imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

		$return = imagejpeg($new_img, "furniturethumbs/". $imgpathexplode[1]);
		
		imageDestroy($img);
		imageDestroy($new_img);
	}
	
	function getIDNumber($tablename, $itemname){
		$message= "";
		require('config/mysql.config.inc');
		$mysqli = new mysqli($host, $username, $password, $db);	

		if($tablename == "CategoryTypes"){$idname = "categoryid"; $name = "cname";}
		if($tablename == "FinishTypes"){$idname = "finishid"; $name = "fname";}
		if($tablename == "ShapeTypes"){$idname = "shapeid"; $name = "sname";}
		if($tablename == "MaterialTypes") {$idname = "materialid"; $name = "mname";}
		if($tablename == "Sets") {$idname = "setid"; $name = "setname";}
		if($tablename == "Pieces") {$idname = "modelno"; $name = "pname";}
		if($tablename == "Types") {$idname = "typeid"; $name = "tname";}
		if($tablename == "Wishlists") {$idname = "wishlistid"; $name = "wname";}
		if($tablename == "Users") {$idname = "uid"; $name = "email";}

		if(isset($idname)){
			$result = $mysqli->query("SELECT " . $idname . " FROM ". $tablename . " WHERE " . $name . " = '" . $itemname . "'");
			if($result->num_rows != 0){
				$ans = $result->fetch_assoc();
				$id = $ans[$idname];
				return $id;
			}
			else{
				$message .="No results!";

			}	
		}
		else{
			$message .= "This function doesn't work with this table\n";
		}

	}
?>
<div class="body_content">
<div class="inner_content">

<?php

//IF WE ARE LOOKING AT A SET DISPLAY THE ITEMS
if(isset($_GET['setid'])){
	//Get the name of the set
	$currsetid = trim($_GET['setid']);
	$result= $mysqli->query("SELECT setname from Sets where setid = '" . $currsetid . "';");
	$arr = $result->fetch_assoc();
	$setname = $arr['setname'];
	
	print "<h2 class=\"content_headers\">$setname</h2>";
	//Figure out what modelno's are in the set
	$result= $mysqli->query("SELECT I.modelno FROM Sets S, InSet I WHERE S.categoryid = '".$categoryid."' AND S.setid = I.setid AND I.setid = '" . $currsetid . "';");
	while($setitems = $result->fetch_assoc()){
		//For each modelno display it's properties
		$mno = trim($setitems['modelno']); 
		$result2 = $mysqli->query("SELECT * FROM Pieces WHERE modelno = '". $mno ."';");
		$item = $result2->fetch_assoc();
		print("\n\t<div class=\"wishlist-piece\">");
		print("<br/>\t\t<h3 class=\"name\">" . $item['pname'] . "</h3>");
		//makeThumb($item['photourl']);
		//print($item['photourl']);
		$url = explode("/", $item['photourl']);
		print("<br/>\t\t<a href=\"furniture.php?page=".$_GET['page']."&amp;modelno=" . $item['modelno'] . "\"><img alt=\"picture\" src=\"furniturethumbs/".$url[1]."\"/> </a>");
		print("<br/>\n\t\t<span class=\"smaller-font\"> Click picture for more details...</span>\n");
		print("<br/>\t\tModel No.: " . $item['modelno']);
		print("\n\t</div>\n");
	}
	
}
else{
	
//IF WE ARE LOOKING AT A SPECIFIC PIECE
	if(isset($_GET['modelno']) && !isset($_GET['addfromlistview'])){
		$modelno = $_GET['modelno'];
		/*Look up the photos with aid equal to $id and store it in an associative array */
		$MOFO = $mysqli->query("SELECT * FROM Pieces WHERE modelno = '".$modelno."'");
		print "<h1 class=\"content_headers\">Detailed View</h1>";
		if($MOFO->num_rows == 0){
			print "<p>Oops! This model number does not exist!</p>" ;
		}
		else{
			while($furniture = $MOFO->fetch_assoc()){
				print("\n\t<div class=\"wishlist-piece\">");
					//Print out each photo along with associated pieces, description, specs, and model number
					print("\t\t<h3 class=\"name\">" . $furniture['pname']). "</h3>";

					//makeThumb($furniture['photourl']);
					$url = explode("/", $furniture['photourl']);
					print("\t\t<img alt=\"picture\" src=\"furniturethumbs/".$url[1]."\"/> ");
					print("<p><em>\t\t". $furniture['description']."</em></p>");

					$temp=$mysqli->query("SELECT tname FROM Types WHERE typeid ='".$furniture['typeid']."'");
					$temp=$temp->fetch_row();
					print("<p>Item: <em>". $temp[0]."</em>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");
					
					$temp=$mysqli->query("SELECT fname FROM FinishTypes WHERE finishid='" . $furniture['finishid'] ."'");
					$temp=$temp->fetch_row();
					print("\t\tFinish: <em>" . $temp[0]."</em>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");

					$temp=$mysqli->query("SELECT mname FROM MaterialTypes WHERE materialid='" . $furniture['materialid'] ."'");
					$temp=$temp->fetch_row();
					print("\t\tMaterial: <em>" . $temp[0]."</em>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");

					$temp=$mysqli->query("SELECT sname FROM ShapeTypes WHERE shapeid='" . $furniture['shapeid'] ."'");
					$temp=$temp->fetch_row();
					print("\t\tShape: <em>" . $temp[0]."</em>");
					print("<br/>\t\tDimensions: " . $furniture['length'] . "x" . $furniture['width'] . "x" . $furniture['height']."&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;");
					print("\t\tModel No.: " . $furniture['modelno']);
					print("</p>");
					
					//TODO: for each set, allow the user to add a piece from that set to a wishlist: use a dropdown menu of wishlists for this	
					if(isset($_GET['addwishlist'])){
						$uid = getIDNumber("Users", $_SESSION['user']);
						$currmodelno = $_GET['modelno'];
						$wishlistid = getIDNumber("Wishlists", $_GET['addwishlist']);
						
						//ADD SQL TO CREATE CUSTOM ID, THEN ADD TO WISHLIST.	
						$query="INSERT into CustomPieces (modelno, categoryid, typeid, finishid, materialid, shapeid, length, width, height) values ('" . $currmodelno . "', '". $categoryid . "','" . $furniture['typeid'] .  "', '" . $furniture['finishid'] .  "', '" . $furniture['materialid'] .  "', '" . $furniture['shapeid'] .  "', '" . $furniture['length'] .  "', '" . $furniture['width'] .  "', '" . $furniture['height'] . "');";
						$result = $mysqli->query($query);
						if($result){							
							$query = "SELECT MAX(customid) as customid FROM CustomPieces WHERE modelno = '" . $currmodelno .  "';"; 
							$result2 = $mysqli->query($query);
							if($result2->num_rows != 0){
								$ans = $result2->fetch_assoc();
								$maxid = $ans['customid'];
								if(isset($maxid)){
									//TODO: CHECK TO SEE IF THIS EXACT PIECE WITH THIS EXACT CONFIG ALREADY EXISTS AND UPDATE QUANTITY
									$query = "INSERT into InWishlist (wishlistid, customid) values ('" . $wishlistid . "', '" . $maxid . "');"; 
									$result2 = $mysqli->query($query);
									if($result2){
										$message = $message . "Successfully added to wishlist";
										print($message);
									}
								}
							}
						}
					}		
					if (isset($_SESSION['user'])) {
						//JUST ADDING TO WISHLIST AS A LOGGED USER
						print("<form action=\"furniture.php\" method=\"get\">");
						$uid = getIDNumber("Users", $_SESSION['user']);
						print("Wishlists:");
						$resultwishlist = $mysqli->query("SELECT * FROM Wishlists WHERE uid = '" . $uid . "' ORDER BY wname;");
						print("<select name=\"addwishlist\">");
						if($resultwishlist->num_rows == 0){
							print "Error: Please Create a Wishlist before you can add this item!<br/>";
						}
						else{
							$i = 0;
							while($wishlist = $resultwishlist->fetch_assoc()){
								$i++;
								print "<option>" . $wishlist["wname"] . "</option>";
							}
						}
						print("</select>");
						print("<input type=\"hidden\" name=\"modelno\" value=\"" . $furniture['modelno'] . "\"/>");
						print("<input type=\"hidden\" name=\"page\" value=\"" . $_GET['page'] . "\"/>");
						print("<input type=\"submit\" value=\"Quick Add to Wishlist\" />");
						print("</form>");
						print("<br/>");
						
						//ADDING AND EDITING AS LOGGED USER
							print("<form action=\"edititem.php\" method=\"get\">");
							$uid = getIDNumber("Users", $_SESSION['user']);
							print("Wishlists:");
							$resultwishlist = $mysqli->query("SELECT * FROM Wishlists WHERE uid = '" . $uid . "' ORDER BY wname;");
							print("<select name=\"addwishlist\">");
							if($resultwishlist->num_rows == 0){
								print "Error: Please Create a Wishlist before you can add this item!<br/>";
							}
							else{
								$i = 0;
								while($wishlist = $resultwishlist->fetch_assoc()){
									$i++;
									print "<option>" . $wishlist["wname"] . "</option>";
								}
							}
							print("</select>");
							print("<input type=\"hidden\" name=\"modelno\" value=\"" . $furniture['modelno'] . "\"/>");							
							print("<input type=\"submit\" value=\"Add and Edit in Wishlist\" />");
							print("</form>");
					}
					else{
						print("<a href=\"useracct.php\"> Add Item To Wishlist </a><br/>");	
						print("<a href=\"useracct.php\"> Edit Item </a>");
					}
				
				//If the user arrived here from the search page, allow them to get back to their search
				if(isset($_SESSION['hasSearched'])){
					print("<br/><br/><a href=\"search.php?search_query2=".$_SESSION['search_query']."&amp;categorymod=".$_SESSION['categorymod']."&amp;typemod=".$_SESSION['typemod']."&amp;finishmod=".$_SESSION['finishmod']."&amp;materialmod=".$_SESSION['materialmod']."&amp;shapemod=".$_SESSION['shapemod']."&amp;queryModified=1&amp;searchmodify=Go\">Back To Previous Page</a");
					unset($_SESSION['hasSearched']);
					unset($_SESSION['search_query']);
					unset($_SESSION['categorymod']);
					unset($_SESSION['typemod']);
					unset($_SESSION['finishmod']);
					unset($_SESSION['materialmod']);
					unset($_SESSION['shapemod']);
					
				}
				else{
					print("<br/><br/><a href=\"furniture.php?page=".$_GET['page']."\">Back To Previous Page</a>");
				}
				print("\n\t</div>\n");
			}
		}
	}
	else{
		
		//if you just quickadded from listview
		if(isset($_GET['addfromlistview']) && isset($_GET['modelno'])){
			$modelno = $_GET['modelno'];
			/*Look up the photos with aid equal to $id and store it in an associative array */
			$DBAG = $mysqli->query("SELECT * FROM Pieces WHERE modelno = '".$modelno."'");
			if($DBAG->num_rows == 1){
			while($furniture = $DBAG->fetch_assoc()){
				//TODO: for each set, allow the user to add a piece from that set to a wishlist: use a dropdown menu of wishlists for this	
				if(isset($_GET['addwishlist'])){
					$uid = getIDNumber("Users", $_SESSION['user']);
					$currmodelno = $_GET['modelno'];
					$wishlistid = getIDNumber("Wishlists", $_GET['addwishlist']);
				
					//ADD SQL TO CREATE CUSTOM ID, THEN ADD TO WISHLIST.	
					$query="INSERT into CustomPieces (modelno, categoryid, typeid, finishid, materialid, shapeid, length, width, height) values ('" . $currmodelno . "', '". $categoryid . "','" . $furniture['typeid'] .  "', '" . $furniture['finishid'] .  "', '" . $furniture['materialid'] .  "', '" . $furniture['shapeid'] .  "', '" . $furniture['length'] .  "', '" . $furniture['width'] .  "', '" . $furniture['height'] . "');";
					$result = $mysqli->query($query);
					if($result){							
						$query = "SELECT MAX(customid) as customid FROM CustomPieces WHERE modelno = '" . $currmodelno .  "';"; 
						$result2 = $mysqli->query($query);
						if($result2->num_rows != 0){
							$ans = $result2->fetch_assoc();
							$maxid = $ans['customid'];
							if(isset($maxid)){
								//TODO: CHECK TO SEE IF THIS EXACT PIECE WITH THIS EXACT CONFIG ALREADY EXISTS AND UPDATE QUANTITY
								$query = "INSERT into InWishlist (wishlistid, customid) values ('" . $wishlistid . "', '" . $maxid . "');"; 
								$result2 = $mysqli->query($query);
								if($result2){
									$message = $message . "Successfully added to wishlist";
									print($message);
								}
							}
						}
					}
				}
			}
		}
	}
		//Display content based on the GET variable
		//if (!($page=null)){ 
		require('config/mysql.config.inc');
		$mysqli= new mysqli($host, $username, $password, $db);
		print("
		<p>At Dining Furniture Showroom, we have furnishings for all tastes, from contemporary, to traditional,
		to country. Choose the style and size that feels right for you from our vast showroom or we can even 
		create one from our own factory.</p> 
		<p>We offer a wide variety of styles and regularly have over 250 collections of dining and kitchen furniture
		as well as over 100 counter stools and islands on display for you to view, it&apos;s worth the trip in to see us.</p>
		");
		//run a query on Sets where categoryid corresponds to the category in the GET variable
		$resultsets= $mysqli->query("SELECT * FROM Sets WHERE categoryid = '".$categoryid."'");
		if($resultsets->num_rows != 0){
			print("<h2 class=\"piece\">Featured " . $page . " Sets</h2>");
		}
		$i = 1;
		print("<div class=\"setswrapper\">");
		while($sets= $resultsets->fetch_assoc()){
		/*
print("\n\t<div class=\"set\">");
			
if($i == 4 || $i == 7 || $i == 10){
				print("\n\t</div>\n");
				print("<div class=\"setswrapper\">");
			}
*/

			print("\n\t<span class=\"set\">");
			$result= $mysqli->query("SELECT I.modelno FROM Sets S, InSet I WHERE S.categoryid = '".$categoryid."' AND S.setid = I.setid AND I.setid = '" . $sets['setid'] . "';");
			$firstitem = $result->fetch_row();
			$firstitem = trim($firstitem[0]);
			$result = $mysqli->query("SELECT * FROM Pieces WHERE modelno = '". $firstitem ."';");
			$itemone = $result->fetch_assoc();
			$t = explode("/", $itemone['photourl']);
			$url = $t[1];
			print("Set $i: <em>" .  $sets['setname']."</em>");
			print("<br/>\t\t<a href=\"furniture.php?page=".$_GET['page']."&amp;setid=" . $sets['setid'] . "\">" . "<img alt=\"picture\" src=\"furniturethumbs/$url\" /> </a>");
			print("<br/>\n\t\t<span class=\"smaller-font\"> Click picture for more details...</span>\n");
			print("\n\t</span>\n");
			/*
if($i == 5 || $i == 8 || $i == 11){
				print("\n\t</div>\n");
			}
*/
			$i++;
		}
		print("</div>");
		
		
		//Below the featured sets, display all of the items in the category dictated by the GET variable
		$result= $mysqli->query("SELECT * FROM Pieces NATURAL JOIN CategoryTypes WHERE categoryid = '".$categoryid."'");
		
		//display each set's picture, description/details, the pieces in it (each set should have its own div)
		print("<h2 class=\"piece\">Individual $page Pieces</h2>");
		while($furniture= $result->fetch_assoc()){
			print("\n\t<div class=\"furniture\">");
			print("<div class=\"furniture_options\">");
			if(isset($_SESSION['user'])){
				//QUICK ADDING TO WISHLIST
				print("<form action=\"furniture.php\" method=\"get\">");
				$uid = getIDNumber("Users", $_SESSION['user']);
				print("Wishlists:");
				$resultwishlist = $mysqli->query("SELECT * FROM Wishlists WHERE uid = '" . $uid . "' ORDER BY wname;");
				print("<select name=\"addwishlist\">");
				if($resultwishlist->num_rows == 0){
					print "Error: Please Create a Wishlist before you can add this item!<br/>";
				}
				else{
					$i = 0;
					while($wishlist = $resultwishlist->fetch_assoc()){
						$i++;
						print "<option>" . $wishlist["wname"] . "</option>";
					}
				}
				print("</select>");
				print("<input type=\"hidden\" name=\"modelno\" value=\"" . $furniture['modelno'] . "\"/>");
				print("<input type=\"hidden\" name=\"page\" value=\"" . $_GET['page'] . "\"/>");
				print("<input type=\"hidden\" name=\"addfromlistview\" value=\"" . "YEAH" .  "\"/>");
				print("<input type=\"submit\" value=\"Quick Add to Wishlist\" />");
				print("</form>");
				print("<br/>");					
				//ADDING AND EDITING AS LOGGED USER		
				print("<form action=\"edititem.php\" method=\"get\">");
				$uid = getIDNumber("Users", $_SESSION['user']);
				print("Wishlists:");
				$resultwishlist = $mysqli->query("SELECT * FROM Wishlists WHERE uid = '" . $uid . "' ORDER BY wname;");
				print("<select name=\"addwishlist\">");
				if($resultwishlist->num_rows == 0){
					print "Error: Please Create a Wishlist before you can add this item!<br/>";
				}
				else{
					$i = 0;
					while($wishlist = $resultwishlist->fetch_assoc()){
						$i++;
						print "<option>" . $wishlist["wname"] . "</option>";
					}
				}
				print("</select>");
				print("<input type=\"hidden\" name=\"modelno\" value=\"" . $furniture['modelno'] . "\"/>");							
				print("<input type=\"submit\" value=\"Add and Edit in Wishlist\" />");
				print("</form>");
			}
			else{
				print("<a href=\"useracct.php\"> Add Item To Wishlist </a><br/><br/>");		
			}
			print("</div>");
			print("<div class=\"furniture_right\"><em>".$furniture['description']."</em></div>");
			print("<div class=\"furniture_left\">");
			//TODO: Print out each photo along with associated pieces, description, specs, and model number
			print("<br/>\t\t" . $furniture['pname']);
	
			//makeThumb($furniture['photourl']);
			$url = explode("/", $furniture['photourl']);
			print("<br/>\t\t<a href=\"furniture.php?page=".$_GET['page']."&amp;modelno=" . $furniture['modelno'] . "\"><img alt=\"picture\" src=\"furniturethumbs/".$url[1]."\"/></a>");
			print("<br/>\n\t\t<span class=\"smaller-font\"> Click picture for more details...</span>\n");
			print("<br/>Model Number<em>: " . $furniture['modelno'])."</em>";
			print("\n\t</div>\n");
			print("\n\t</div>\n");
		}	
}
}

	//Close the connection to the database
	$mysqli->close();
	unset($_SESSION['hasSearched']);
	print("</div></div>");
include ('includes/footer.php');
?>

</body>
</html>
